package com.lemon.smartsafety.ui.activity.safe.nfcandqrcode;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.view.SpacesItemDecoration;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.DataInfo;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.datacoll.BuildingRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.inspection.InspectionCheckItemStepTwoFinishEvent;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.InspectionServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.result.OldBaseMode;
import com.lemon.smartsafety.result.safe.ResultCheckNfc;
import com.lemon.smartsafety.tag.BaseTAG;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.ui.adapter.safe.nfcorqrcode.CodeCheckItemFlowAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class CodeInspectionStepOneActivity extends PhotoSelectBaseActivity implements RecyclerTClickListener<ResultCheckNfc.FlowListEntity> {

    private LoggerHelper loggerHelper = new LoggerHelper(CodeInspectionStepOneActivity.class);


    @Bind(R.id.tv_tip)
    TextView tvTip;
    @Bind(R.id.tv_remark)
    TextView tvRemark;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.btn_view_record)
    Button btnViewRecord;

    @Bind(R.id.ll_evidence)
    LinearLayout llEvidence;


    /**
     * bundle info
     */
    private String strCode = "";


    private String sCheckId = "";
    private List<ResultCheckNfc.FlowListEntity> mFlows = new ArrayList<>();

    private CodeCheckItemFlowAdapter mAdapter;
    SpacesItemDecoration mItemDecoration;

    private ResultCheckNfc resultCheckNfc;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            strCode = getIntent().getStringExtra(BaseTAG.COMMON_BASE_TAG);
        }
    }

    @Override
    protected void initTitle() {
        setBarTitle(R.string.safe_title);
    }

    @Override
    protected void callFinish() {
        IApplication._tempOneActivity = null;
        AppManager.getAppManager().finishActivity(CodeInspectionStepOneActivity.this);
        System.gc();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_code_inspection_step_one;
    }


    @Override
    protected void initViews() {
        super.initViews();
        if (CommonUtil.strIsEmpty(strCode)) {
            callFinish();
            return;
        }


        int spacingInPixels = recyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.height_one_px);
        mItemDecoration = new SpacesItemDecoration(spacingInPixels);

        mAdapter = new CodeCheckItemFlowAdapter(mFlows, this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
        recyclerView.addItemDecoration(mItemDecoration);
        Log.v("strCode is ",strCode);
        bindCodeHttp(strCode);

        IApplication._tempOneActivity = this;
    }

    /**
     * 刷新 View
     */
    private void refreshView() {

        initViewValue();

        setFlowList(resultCheckNfc.getFlowList());
    }


    private void initViewValue() {
        tvTip.setText(resultCheckNfc.getAddress());
        tvRemark.setText(StringUtils.nullValue(resultCheckNfc.getRemark(), "无"));

        if (!StringUtils.getBoolean(resultCheckNfc.getIsPatrol())) {//不是巡更点就隐藏掉那个证据了。
            //setSelectEnable(false);
            llEvidence.setVisibility(View.GONE);
        } else {
            llEvidence.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void initListener() {
        super.initListener();
    }


    @OnClick({R.id.btn_submit, R.id.btn_view_record})
    public void onclickAction(View view) {
        if (view.getId() == R.id.btn_submit) {
            if (!validateForm()) {
                return;
            }
            getConfirmDialog("是否结束检查？", new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        doSubmitAction();
                    }
                }
            }).show();

        } else if (view.getId() == R.id.btn_view_record) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseTAG.ResultCheckNfc_ItemDATA, resultCheckNfc);
            UIHelper.showActivity(this, bundle, CodeInspectionCheckItemRecordActivity.class);
        }
    }

    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams();
        params.put("item_id", resultCheckNfc.getItemId());
        params.put("check_id", sCheckId);

        if (StringUtils.getBoolean(resultCheckNfc.getIsPatrol())) {//如果是巡更点
            getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
                @Override
                public void onStart() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mHUDUtil.showHUD();
                        }
                    });
                }

                @Override
                public void onFinish(List<UploadFileItem> data) {
                    if (data != null && data.size() != 0) {
                        params.put("files", mGson.toJson(data));
                    }
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            InspectionServices.init().saveInspectionCheck(params);
                        }
                    });
                }
            });
        } else {
            InspectionServices.init().saveInspectionCheck(params);
        }
    }

    /**
     * 是否需要维保
     *
     * @return
     */
    public boolean getGoRepair() {
        List<ResultCheckNfc.FlowListEntity> items = mAdapter.getData();
        boolean result = false;
        if (null != items && items.size() != 0) {
            for (int i = 0; i < items.size(); i++) {
                String statusString = items.get(i).getStatus();
                if (DataInfo.RED_TAG.equals(statusString) || DataInfo.YELLOW_TAG.equals(statusString)) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }


    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        if (StringUtils.getBoolean(resultCheckNfc.getIsPatrol()) && !hasEvidence()) {
            mHUDUtil.showErrorTip("巡更点必须要采集材料证据");
            return false;
        }
        return true;
    }

    @Override
    public void evidencePlusEventHandler(String tag) {
        if (this.getClass().getName().equals(tag)) {
            showActionSheet(EvidenceActionSheetType.CAMERA_VOICE);
        }
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
      if (EventTag.TAG_INSPECTION_CHECK_ACTION.equals(event.getTag())) {//检查结束Action
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    //sCheckId != null && sCheckId.length() != 0 && getGoRepair()   这里跳转到上报维修哪里
                    mHUDUtil.showInfoTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            BuildingRefreshEvent refreshEvent = new BuildingRefreshEvent();
                            refreshEvent.setTag(EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_REFRESH);
                            AppService.getBus().post(refreshEvent);
                            callFinish();

                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        }
    }


    private void setFlowList(List<ResultCheckNfc.FlowListEntity> vo) {
        if (!CommonUtil.listIsEmpty(vo)) {
            mFlows.clear();
            mFlows.addAll(vo);
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        }

    }


    @Subscribe
    public void onEventMainThread(InspectionCheckItemStepTwoFinishEvent event) {
        sCheckId = StringUtils.nullValue(event.getData().getId());
        bindCodeHttp(strCode);
    }


    @Override
    public void onItemClick(ResultCheckNfc.FlowListEntity data, int position) {
        sCheckId = StringUtils.nullValue(sCheckId);
        Bundle bundle = new Bundle();
        bundle.putSerializable(BaseTAG.ResultCheckNfc_ItemDATA, resultCheckNfc);
        bundle.putSerializable(BaseTAG.ResultCheckNfc_CheckDATA, resultCheckNfc.getFlowList().get(position));
        bundle.putString(BundleKey.SAFE_INSPECTION_CHECK_ID, sCheckId);
        UIHelper.showActivity(this, bundle, CodeInspectionStepTwoActivity.class);
    }


    public void bindCodeHttp(String code) {
        LemonRequestParams params = new LemonRequestParams("", "", "");
        params.put("nfc_code", code);
        params.put("qrcode_code", code);
        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(this);
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.CheckNfc);
        Logger.i(serverUrl);
        Logger.i(params.toString());
        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, serverUrl, "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                Logger.i("result\n"+result);
                if (httpClient) {
                    OldBaseMode baseMode = JsonUtils.fromJson(result, OldBaseMode.class);
                    Logger.i("baseMode\nmsg="+baseMode.getMsg()+"\n" +
                            "error_msg="+baseMode.getError().getMsg() +
                            "error_code="+baseMode.getError().getCode()
                            +"\nresult="+baseMode.getResult());
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (!baseMode.isIsError()) {
                            //刷新当前页面
                            resultCheckNfc = JsonUtils.fromJson(mGson.toJson(baseMode.getResult()), ResultCheckNfc.class);
                            if (!CommonUtil.objIsEmpty(resultCheckNfc)) {
                                refreshView();
                            } else {
                                ToastUtil.show("数据类型有误");
                                finish();
                            }

                        } else {
                            //mHUDUtil.showErrorTip(baseMode.getError().getMsg());
                            ToastUtil.show(baseMode.getError().getMsg());
                            finish();
                        }
                    }
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(EventTag.TAG_INSPECTION_CHECK_ITEM_FLOW);
        IApplication._tempOneActivity = null;

        mHUDUtil.hidden();
    }

}
